package controller.business.observerReport;

import base.response.OffsetLimitPage;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.business.BusinessInfoServices;
import services.business.InspectorInfoServices;
import services.business.ObserverReportServices;
import util.DateUtil;
import util.io.UploadDownloadFileUtil;
import util.key.IDFactory;
import validator.NotBlankFluentValidator;
import validator.SizeFluentValidator;
import wt.entity.business.*;
import wt.staticData.ShortData;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("business/observerReport")
public class ObserverReportController extends BaseController {
    @Autowired
    ObserverReportServices observerReportServices;
    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    InspectorInfoServices inspectorInfoServices;


    @RequiresPermissions("business:observerReport:default")
    @RequestMapping("index")
    public String index(Short observerIsReport, Map map) {
        map.put("observerIsReport", observerIsReport);
        return "business/observerReport/index";
    }


    @RequiresPermissions("business:observerReport:default")
    @RequestMapping("editDlg")
    public String editDlg(String businessId, Map map) throws Exception {

        map.put("businessId", businessId);
        map.put(StaticConstant.EDIT_URL, "business/observerReport/insert");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);
        return "business/observerReport/editDlg";
    }

    @RequiresPermissions("business:observerReport:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult insert(ObserverReport observerReport) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(observerReport.getBusinessId(), new NotBlankFluentValidator("业务编号"))
                .on(observerReport.getCheckStatus(), new NotBlankFluentValidator("核查情况描述"))
                .on(observerReport.getCheckDiscipline(), new NotBlankFluentValidator("纪律执行描述"))
                .on(observerReport.getMatter(), new SizeFluentValidator(0, 1, "纪律执行是否有问题"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }

        observerReport.setAssessTime(new Date());


        observerReportServices.insertSelective(observerReport, observerReport.getBusinessId());
        return commonResult.setSuccess();
    }


    @RequiresPermissions("business:observerReport:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(
            String companyName,
            String productName,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            Short observerIsReport,
            Integer offset,
            Integer limit
    ) throws Exception {

        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        BusinessInfoExample.Criteria criteria = businessInfoExample.createCriteria();
        businessInfoExample.setOrderByClause("ID DESC");
        criteria.andObserverIdEqualTo(getLoginAccount().getStaffInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3);

        if (!StringUtils.isBlank(companyName)) {
            criteria.andCompanyNameLike("%" + companyName + "%");
        }

        if (!StringUtils.isBlank(productName)) {
            criteria.andProductNameLike("%" + productName + "%");
        }

        if (startTime != null) {
            criteria.andEndTimeGreaterThanOrEqualTo(startTime);
        }

        if (endTime != null) {
            criteria.andEndTimeLessThan(DateUtil.moveDate(endTime, 1));
        }

        if (observerIsReport != null) {
            criteria.andObserverIsReportEqualTo(observerIsReport);

        }

        return businessInfoServices.selectByExample(businessInfoExample, offset, limit);
    }


    @RequiresPermissions("business:observerReport:default")
    @ResponseBody
    @RequestMapping("welcomeTips")
    public CommonResult welcomeTips() throws Exception {
        CommonResult commonResult = new CommonResult();
        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        businessInfoExample.createCriteria().andObserverIdEqualTo(getLoginAccount().getStaffInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3).andObserverIsReportEqualTo(ShortData.s0);
        int count = businessInfoServices.countByExample(businessInfoExample);

        if (count == 0) {
            return commonResult.setError();
        } else {
            Map map = new HashMap();
            map.put("info", count + "份现场核查报告未填写");
            map.put("url", "business/observerReport/index?observerIsReport=0");
            commonResult.setData(map);
            return commonResult.setSuccess();
        }
    }


    @RequestMapping("pdf/{businessId}")
    public ResponseEntity<byte[]> pdf(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);

        ObserverReportExample observerReportExample = new ObserverReportExample();
        observerReportExample.createCriteria().andBusinessIdEqualTo(businessId);
        ObserverReport observerReport = observerReportServices.selectByExample(observerReportExample).get(0);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);
        String leaderName = "", crewsName = "";
        for (InspectorInfo inspectorInfo : inspectorInfoList) {
            if ("leader".equals(inspectorInfo.getExpertRole())) {
                leaderName = inspectorInfo.getExpertName();
            } else {
                crewsName += inspectorInfo.getExpertName() + "，";
            }
        }
        crewsName = crewsName.substring(0, crewsName.length() - 1);//去除最后的“，”

        Map<String, String> map = new HashMap<String, String>();
        map.put("title", "上海市" + businessInfo.getItemName() + "现场核查观察工作报告");
        map.put("observerName", businessInfo.getObserverName());
        map.put("businessCode", businessInfo.getBusinessCode());
        map.put("companyName", businessInfo.getCompanyName());
        map.put("businessType", businessInfo.getBusinessType());
        map.put("productName", businessInfo.getProductName());
        map.put("result", businessInfo.getResult());
        map.put("noticeTime", DateUtil.date2String(businessInfo.getArrangeStartTime(), "yyyy-MM-dd"));
        map.put("checkTime", DateUtil.date2String(businessInfo.getEndTime(), "yyyy-MM-dd"));
        map.put("leader", leaderName);
        map.put("crew", crewsName);
        map.put("checkStatus", observerReport.getCheckStatus());
        map.put("checkDiscipline", observerReport.getCheckDiscipline());
        map.put("remark", observerReport.getRemark());


        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ObserverReportPdf.createPdf(FileUtils.openOutputStream(file), map);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("现场核查观察工作报告.pdf", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

    @RequestMapping("doc/{businessId}")
    public ResponseEntity<byte[]> doc(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);

        ObserverReportExample observerReportExample = new ObserverReportExample();
        observerReportExample.createCriteria().andBusinessIdEqualTo(businessId);
        ObserverReport observerReport = observerReportServices.selectByExample(observerReportExample).get(0);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);
        String leaderName = "", crewsName = "";
        for (InspectorInfo inspectorInfo : inspectorInfoList) {
            if ("leader".equals(inspectorInfo.getExpertRole())) {
                leaderName = inspectorInfo.getExpertName();
            } else {
                crewsName += inspectorInfo.getExpertName() + "，";
            }
        }
        crewsName = crewsName.substring(0, crewsName.length() - 1);//去除最后的“，”

        Map<String, String> map = new HashMap<String, String>();
        map.put("title", "上海市" + businessInfo.getItemName() + "现场核查观察工作报告");
        map.put("observerName", businessInfo.getObserverName());
        map.put("businessCode", businessInfo.getBusinessCode());
        map.put("companyName", businessInfo.getCompanyName());
        map.put("businessType", businessInfo.getBusinessType());
        map.put("productName", businessInfo.getProductName());
        map.put("result", businessInfo.getResult());
        map.put("noticeTime", DateUtil.date2String(businessInfo.getArrangeStartTime(), "yyyy-MM-dd"));
        map.put("checkTime", DateUtil.date2String(businessInfo.getEndTime(), "yyyy-MM-dd"));
        map.put("leader", leaderName);
        map.put("crew", crewsName);
        map.put("checkStatus", observerReport.getCheckStatus());
        map.put("checkDiscipline", observerReport.getCheckDiscipline());
        map.put("remark", observerReport.getRemark());


        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ObserverReportDoc.createDoc(FileUtils.openOutputStream(file), map);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("现场核查观察工作报告.doc", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

}
